package com.john.demo.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.john.demo.bio.SocketUtils.readLine;
import static com.john.demo.bio.SocketUtils.writeLine;

/**
 * 基于BIO Socket的CS通信
 * @author John
 *
 */
public class SocketServer {

	// 创建10个线程大小的固定线程池，同时最大能连接10个客户端
	private ExecutorService threadPool = Executors.newFixedThreadPool(10);

	public static void main(String[] args) {
		SocketServer ss = new SocketServer();
		System.out.println("start socket server. on 127.0.0.1:10099");
		ss.startServer();
	}

	public void startServer() {
		try {
			ServerSocket ss = new ServerSocket(10099);
			Socket socket = null;
			while ((socket = ss.accept()) != null) {
				handleSocket(socket);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void handleSocket(final Socket socket) {
		// 获取客户端IP
		String ip = ((InetSocketAddress)socket.getRemoteSocketAddress()).getHostName();
		System.out.println("客户端("+ip+")已上线.");
		threadPool.execute(() -> {
			// 给客户端发送欢迎消息
			writeLine(socket, "欢迎来到蓝鸥聊天室！");
			Scanner sc = new Scanner(System.in);
				// 读消息线程
				new Thread(()->{
					while(true) {
						String receiveMsg = readLine(socket);
						if(receiveMsg != null) {
							System.out.println("客户端("+ip+")：" + receiveMsg);
						}
					}
				}).start();
				// 写消息线程
				new Thread(()->{
					while(true) {
						String writeMsg = sc.nextLine();
						writeLine(socket, writeMsg);
					}
				}).start();
		});
	}

}
